
/**
 * @copyright Copyright (c) 2025 
 * CSG Digital Grid Technology (Guangdong) Co., Ltd.
 * @author xxxcsg
 * @brief OpenHarmony 轻量系统升级服务（UpdateLiteService）实现
 * @details 基于 OpenHarmony SAMGR 框架的系统升级服务，核心功能如下：
 *          1. 服务注册：通过 SYS_SERVICE_INIT 注册为系统服务，提供 UPDATE_LITE_SAMGR_SERVICE 服务标识
 *          2. 线程管理：初始化时创建独立升级线程（UpdateLiteThread），配置线程属性（优先级、栈大小等）
 *          3. 连接初始化：通过 InitConnect 函数初始化 MQTT 协议的 OTA 升级连接
 *          4. 服务接口：实现 SAMGR 服务必需的 GetName/Initialize/MessageHandle/GetTaskConfig 接口
 *          5. 日志输出：通过 HILOG 打印服务启动、线程运行等关键日志信息
 * @note 1. 依赖 OpenHarmony 系统组件：samgr_lite、thread_adapter、hilog 等
 *       2. 依赖升级相关模块：update_lite_service.h、update_lite_manager.h
 *       3. 注释代码包含 MQTT 遥测数据发送、OTA 登录登出等预留功能，可根据需求启用
 * @attention 1. 服务注册需确保 UPDATE_LITE_SAMGR_SERVICE 标识在系统中唯一
 *            2. 线程栈大小（1024）、优先级（2）等配置需根据系统资源情况调整
 *            3. 需提前实现 InitConnect 函数的具体逻辑（MQTT 连接建立），否则服务初始化失败
 */
#include <stdio.h>
#include <unistd.h>
#include "ohos_types.h"
#include "ohos_init.h"
#include "hilog/log.h"
#include "thread_adapter.h"
#include "time_adapter.h"
#include "iunknown.h"
#include "service.h"
#include "samgr_lite.h"
//#include "mqtt_ota.h"


#include "update_lite_service.h"
#include "ohos_init.h"
#include "ohos_types.h"
#//include "utils_log.h"

#include "update_lite_manager.h"




static const char *GetName(Service *service);
static BOOL Initialize(Service *service, Identity identity);
static BOOL MessageHandle(Service *service, Request *msg);
static TaskConfig GetTaskConfig(Service *service);


static void Call(IUnknown *iUnknown)
{
    HILOG_INFO(LOG_CORE, "[LPC Call API][thread:%u]\n", pthread_self());
    (void)iUnknown;
}

static UpdateLiteService g_updateLiteService = {
    .GetName = GetName,
    .Initialize = Initialize,
    .MessageHandle = MessageHandle,
    .GetTaskConfig = GetTaskConfig,
    DEFAULT_IUNKNOWN_ENTRY_BEGIN,
    .Call = Call,
    DEFAULT_IUNKNOWN_ENTRY_END,
};

static const char *GetName(Service *service)
{
    return UPDATE_LITE_SAMGR_SERVICE;
}
/*
uint32_t InitService(void)
{
    //IOTA_login();

    // 保持程序运行，发送遥测数据
    int aaa = 0;
    while (true) {
        // 这里可以添加发送遥测数据的代码
        sleep(30);
        HILOG_INFO(LOG_CORE, "TaskEntry Enter....[%d]--------aaa = %d ", pthread_self(), aaa++);
        //(void)pause();
        //publishMessage(TELEMETRY_TOPIC, "{\"PA\":\"22.54845664\",\"TEM\":\"114.06455184\"}");
    }


    //IOTA_logout();
    //IOTA_destroy();

    return 0;
}

static void *TaskEntry(void *argv)
{
    HILOG_INFO(LOG_CORE, "TaskEntry Enter....[%d]", pthread_self());

    if (InitService() != 0) {
        HILOG_ERROR(LOG_CORE, "init service failed");
        return FALSE;
    }

    printf("hello TaskEntry! --  end\n");

    return NULL;
}
*/

static void *UpdateLiteThread(void *argv)
{
    HILOG_INFO(LOG_CORE, "UpdateLiteThread Enter....[%d]", pthread_self());

    // 初始化OTA升级连接
    if (InitConnect(UPDATELITE_MQTT) != 0) {
    //if (InitService() != 0) {
        HILOG_ERROR(LOG_CORE, "init service failed");
        return FALSE;
    }
    HILOG_INFO(LOG_CORE, "hello UpdateLiteThread! --  to pause()\n");
    (void)pause();
    HILOG_INFO(LOG_CORE, "hello UpdateLiteThread! --  end\n");

    return NULL;
}

static BOOL Initialize(Service *service, Identity identity)
{
    UpdateLiteService *updateLiteService = (UpdateLiteService *)service;
    updateLiteService->identity = identity;

    ThreadAttr attr = {"collector thread", 1024, 2, 0, 0};
    ThreadId threadId = (ThreadId)THREAD_Create(UpdateLiteThread, NULL, &attr);

    HILOG_INFO(LOG_CORE, "collector service[%s], thread[%u] starting, Time: [%11u]"
            , service->GetName(service), threadId, SAMGR_GetProcessTime());
    return TRUE;
}

static BOOL MessageHandle(Service *service, Request *msg)
{
    HILOG_INFO(LOG_CORE, "[LPC MessageHandle][thread:%u] msgId<%d>: %s \n",
            pthread_self(), msg->msgId, (char *)msg->data);
    (void)service;
    return FALSE;
}

static TaskConfig GetTaskConfig(Service *service)
{
    HILOG_INFO(LOG_CORE, "[LPC GetTaskConfig][thread:%u]\n", pthread_self());
    (void)service;
    TaskConfig config = {LEVEL_HIGH, PRI_BELOW_NORMAL, 0x800, 20, SHARED_TASK};
    return config;
}

static void Init(void)
{
    HILOG_INFO(LOG_CORE, "update_lite_service.c --- ....Init()-------");

    BOOL isRegistered = SAMGR_GetInstance()->RegisterService((Service *)&g_updateLiteService);
    if (!isRegistered) {
        HILOG_INFO("[RegisterService S:%s] init service failed!", UPDATE_LITE_SAMGR_SERVICE);
        return;
    }
    // isRegistered = SAMGR_GetInstance()->RegisterDefaultFeatureApi(UPDATE_LITE_SAMGR_SERVICE, GET_IUNKNOWN(g_updateLiteService));
    // if (!isRegistered) {
    //     HILOG_INFO("[RegisterService S:%s] init RegisterDefaultFeatureApi failed!", UPDATE_LITE_SAMGR_SERVICE);
    //     return;
    // }
    HILOG_INFO("[RegisterService S:%s] init service success!", UPDATE_LITE_SAMGR_SERVICE);
}
SYS_SERVICE_INIT(Init);

